<?php
class Rss_Parser
{
    public $url;
    public $content;

    public function __construct($url = null)
    {
        $this->url = $url;
    }

    /**
     * Load rss from XML string
     * @param $xml
     */
    public function load_xml($xml)
    {
        $this->content = $xml;
    }

    public function load_url($url) {
        $this->url = $url;
    }

    public function get_items()
    {
        // Load rss from url
        $this->load();
        try {
            $xml = simplexml_load_string($this->content);

            if (is_null($xml) || !$xml) {
                return null;
            }
            $items = array();

            foreach ($xml->channel->item as $item) {
                $items[] = $item;
            }

            return $items;
        } catch (Exception $e) {
            return null;
        }
    }

    public function write($path)
    {
        if (!is_null($this->content)) {
            file_put_contents($path, $this->content);
            return true;
        }

        return false;
    }

    public static function get_items_from_url($url)
    {
        $self = new Rss_Parser($url);
        $self->load();
        return $self->get_items();
    }

    public static function get_items_from_string($xml)
    {
        $self = new Rss_Parser();
        $self->load_xml($xml);
        return $self->get_items();
    }

    protected function load()
    {
        if (is_null($this->url)) {
            throw new Exception("Invalid URL ($this->url)");
        }
        $this->content = file_get_contents($this->url);
    }
}